#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import sys as osSys
import getopt as osGetopt
from os import popen as osPopen  # 管道处理
from time import sleep as osSleep
import uiautomator2 as U2
import logging.config

from utils.tools import Tools
# 全局 global
import gol

gol._init()


class App():
    def __init__(self):
        self.sAction = None  # 执行动作
        self.sSerial = None  # 设备序列
        self.iDeviceIndex = None  # 设备序列索引
        self.sActionType = None  # 执行动作
        self.iLen = None  # 数量
        self.aDeviate = [13, 50]  # 偏移量范围，上划时使用
        self.sVal = None  # 输入内容
        self.iNextIndex = None  # 跳过索引
        self.iBrightness = 0 # 屏幕亮度
        self.bStart = True
        self.bLog = True
        # self.iStepTime = 0
        gol.set('iStepTime', 0)
        # logger = logging.getLogger()
        # logger.setLevel(logging.WARNING)

        try:
            (opts, args) = osGetopt.gnu_getopt(osSys.argv[1:], "ha:s:t:v:i:b:st:log", ["help", "action=", "serial=", "type=", "len=", "val=", "index=", "brightness=", "di=", "st=", "log="])
            # print(opts, args)
        except osGetopt.GetoptError as sErr:
            print('ERROR:', sErr)
            osSys.exit(2)

        for opt, arg in opts:
            # print(opt, arg)
            if opt == '-h':
                print('test.py -a <action> -i <nextIndex>')
                osSys.exit()
            elif opt in ("-a", "--action"):
                self.sAction = arg
            elif opt in ("-s", "--serial"):
                self.sSerial = arg
            elif opt in ("-t", "--type"):
                self.sActionType = arg
            elif opt in ("--len"):
                self.iLen = int(arg)
            elif opt in ("-v", "--val"):
                self.sVal = arg
            elif opt in ("-i", "--index"):
                self.iNextIndex = int(arg)
            elif opt in ("-b", "--brightness"):
                self.iBrightness = arg
            elif opt in ("--di"):
                self.iDeviceIndex = int(arg)
            elif opt in ("--st"):
                self.bStart = bool(int(arg))
            elif opt in ("--log"):
                self.bLog = bool(int(arg))

        if (self.iDeviceIndex != None):
            aDevices = self.getDeviceidList()
            if (aDevices[int(self.iDeviceIndex)]):
                self.sSerial = aDevices[int(self.iDeviceIndex)]
                nameShell = 'adb -s ' + self.sSerial + ' shell getprop ro.product.name'
                print(self.sSerial, osPopen(nameShell).readlines()[0])
        else:
            if (not self.sSerial):
                aDevices = self.getDeviceidList()
                iDevices = len(aDevices)
                if (iDevices > 1):
                    self.getPhoneList(aDevices)
                    iInputIndex = input("选择设备序号")
                    self.sSerial = aDevices[int(iInputIndex)]
                else:
                    self.sSerial = aDevices[0]

        # 传入值
        self.sAdb = 'adb -s ' + self.sSerial + '' if self.sSerial else 'adb'  # 单设备或多设备
        gol.set("sAdb", self.sAdb)
        gol.set("sActionType", self.sActionType)
        gol.set("sVal", self.sVal)

        self._d = U2.connect(self.sSerial)
        # self._d.settings['xpath_debug'] = False

        if (self.bLog):
            logging.config.dictConfig({
                'version': 1,
                'disable_existing_loggers': True,
            })

        # 初始一下tools的 adb 值
        self.tool = Tools()
        
        self.tool.toLight()

    def getDeviceidList(self):
        return list(Tools().getDeviceid())

    def getPhoneList(self, aDevices):
        for iIndex in range(len(aDevices)):
            nameShell = 'adb -s ' + aDevices[iIndex] + ' shell getprop ro.product.name'
            print('%d: %s %s' % (iIndex, aDevices[iIndex], osPopen(nameShell).readlines()[0]))


    def appInfo(self):
        return self._d.info

    # 获取当前应用程序信息
    def appCurrent(self):
        return self._d.app_current()

    # 节点封装
    def el2(self, sType, sVal, iTimeout=2):
        oNode = None
        bNode = False
        if (sType == 't'):
            oNode = self._d(text=sVal)
        elif (sType == 'tc'):
            oNode = self._d(textContains=sVal)
        elif (sType == 'tm'):
            oNode = self._d(textMatches=sVal)
        elif (sType == 'ts'):
            oNode = self._d(textStartsWith=sVal)
        elif (sType == 'd'):
            oNode = self._d(description=sVal)
        elif (sType == 'dc'):
            oNode = self._d(descriptionContains=sVal)
        elif (sType == 'dm'):
            oNode = self._d(descriptionMatches=sVal)
        elif (sType == 'ds'):
            oNode = self._d(descriptionStartsWith=sVal)
        elif (sType == 'c'):
            oNode = self._d(className=sVal)
        elif (sType == 'cm'):
            oNode = self._d(classNameMatches=sVal)
        elif (sType == 'id'):
            oNode = self._d(resourceId=sVal)
        elif (sType == 'idm'):
            oNode = self._d(resourceIdMatches=sVal)
        elif (sType == 'p'):
            oNode = self._d.xpath(sVal)
        bNode = oNode.exists(timeout=iTimeout) if sType != 'p' else oNode.exists
        return bNode, oNode

    def el2CE(self, sType, sVal, iTimeout=2):
        bNode, oNode = self.el2(sType, sVal)
        if bNode:
            return oNode.click_exists(timeout=iTimeout)
        return bNode

    def myEcho(self, sTxt, bVal=True):
        sEffectTxt = '成功' if bVal else '失败'
        print("--- %s - %s ---" % (sTxt, sEffectTxt))

    def tapNode(self, sType, sVal, bClick=1, timeout=2):
        bNode, oNode = self.el2(sType, sVal)
        if bNode and bClick == 1:
            oNode.click(timeout)
        self.myEcho(sVal, bNode)
        return bNode, oNode

    def getXml(self):
        nodeXml = self._d.dump_hierarchy()
        print(nodeXml)
        return nodeXml

    def screen(self, sAction):
        if (sAction == 'on'):
            self._d.screen_on()
        else:
            self._d.screen_off()


    def countDown(self, sType='', iSleepStep = 10, isMove = False):
        if (gol.get('iStepTime') <= 0):
            return
        if (sType):
            tupMoveVal = Tools.moveDirection(sType)
        while gol.get('iStepTime') > 0:
            if (gol.get('iStepTime') <= 0):
                break
            if (sType and gol.get('iStepTime') % iSleepStep == 0 and gol.get('iStepTime') > 5 and isMove):
                Tools().move(tupMoveVal)

            print("\r", end="")
            print("倒计时: {0}".format(gol.get('iStepTime')).rstrip('0'), end="")
            osSys.stdout.flush()
            gol.set('iStepTime', int(gol.get('iStepTime') - 1))
            osSleep(1)


    def isNotEmpty(self, value):
        return value is not None and value != "" and (value if isinstance(value, (list, tuple)) else True)

if __name__ == "__main__":
    app = App()
    # app.getPhoneList()